package com.tjetc.service.impl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import com.tjetc.dao.ChatHistoryMapper;
import com.tjetc.domain.ChatHistory;
import com.tjetc.repository.ChatHistoryDao;
import com.tjetc.repository.UserDao;
import com.tjetc.service.ChatHistoryService;
import com.tjetc.vo.ChatHistoryCategory;
import com.tjetc.vo.Result;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.*;

@Service
public class ChatHistoryServiceImpl implements ChatHistoryService {
    @Resource
    private ChatHistoryMapper chatHistoryMapper;
    @Resource
    private ChatHistoryDao chatHistoryDao;
    @Resource
    private ElasticsearchClient client;
    @Resource
    private UserDao userDao;
    @Override

    public Result add(ChatHistory chatHistory) {

            if (chatHistoryMapper.insert(chatHistory) == 1) {
                try {
                    System.out.println(chatHistory);
                    chatHistory.setDate(new Date(chatHistory.getDate().getTime()+1000*60*60*8));
                    chatHistoryDao.save(chatHistory);
                    System.out.println("插进来了!!!!");
//                    System.out.println("进入ES后的记录"+chatHistoryDao.findById(chatHistory.getId()));

                    return Result.ok().setCode(200);
                } catch (Exception e) {
                    e.printStackTrace();
                    chatHistoryMapper.deleteByPrimaryKey(chatHistory.getId());
                    return Result.fail().setCode(500).setMsg("ES添加失败");
                }
            }else {

                return Result.fail().setCode(500).setMsg("数据库添加失败");

            }



    }
    @Override
    public void test() {
        System.out.println("客服发的消息"+chatHistoryDao.findAllBySenderIdAndReceiverIdOrderByDate(8,1));
        System.out.println("用户发的消息"+chatHistoryDao.findAllBySenderIdAndReceiverIdOrderByDate(1,8));


    }

    @Override
    public Result del(Integer id) {



       if (chatHistoryMapper.deleteByPrimaryKey(id) == 1){
           try{
               chatHistoryDao.deleteById(id);
               return Result.ok().setCode(200);
           }catch (Exception e){
               e.printStackTrace();
               return Result.fail().setCode(500).setMsg("ES删除失败");
           }
       }else {
           return Result.fail().setCode(500).setMsg("数据库删除失败");
       }

    }

    @Override
    public List<ChatHistory> findAllById(Integer senderId, Integer receiveId) throws IOException {
        if (client.indices().exists(b -> b.index("chathistory")).value()){
//            System.out.println("===================有这个索引");
            List<ChatHistory>chatHistories= chatHistoryDao.findAllBySenderIdAndReceiverIdOrderByDate(senderId,receiveId);
            if (chatHistories.size()==0){
                System.out.println("ES没有查到======================");
                List<ChatHistory>chatHistories1= chatHistoryMapper.findAllBysenderIdAndReceiverId(senderId,receiveId);
                chatHistoryDao.saveAll(chatHistories1);
                return chatHistories1;
            }else {
                System.out.println("ES查到了!!!!!!!!!!!!!!!!");
                return chatHistories;
            }
        }else {
//            System.out.println("===================没有这个索引");
            List<ChatHistory>chatHistories1= chatHistoryMapper.findAllBysenderIdAndReceiverId(senderId,receiveId);
            chatHistoryDao.saveAll(chatHistories1);
            return chatHistories1;
        }





    }

    @Override
    public List<ChatHistoryCategory> chatHistoryCategoryList(Integer userId) throws IOException {
        List<ChatHistory> chatHistories1 =chatHistoryDao.findAllBySenderId(userId);
//        System.out.println("chatHistories1 = " + chatHistories1);
        List<ChatHistory> chatHistories2 =chatHistoryDao.findAllByReceiverId(userId);
//        System.out.println("chatHistories2 = " + chatHistories2);
        HashSet<Integer> otherUserId = new HashSet<>();
        for (ChatHistory chatHistory : chatHistories1){
            otherUserId.add(chatHistory.getReceiverId());
        }
        for (ChatHistory chatHistory : chatHistories2){
            otherUserId.add(chatHistory.getSenderId());
        }
        List<ChatHistoryCategory> chatHistoryCategoryList=new ArrayList<>();
        for (Integer integer : otherUserId) {
            Integer readcount=0;
           String avatar=userDao.findById(integer).get().getAvatar();
           String username=userDao.findById(integer).get().getUsername();
           List<ChatHistory> chatHistories11=findAllById(userId,integer);
            List<ChatHistory> chatHistories22=findAllById(integer,userId);
//            System.out.println("chatHistories11 = " + chatHistories11);
//            System.out.println("chatHistories22 = " + chatHistories22);
            for (ChatHistory chatHistory : chatHistories22) {
                if (!chatHistory.getIsRead()){
                    System.out.println("chatHistory = " + chatHistory);
                    readcount++;
                }
            }
            System.out.println(username+"的未读"+readcount+"条");
            List<ChatHistory> chatHistories=new ArrayList<>(chatHistories11);
            chatHistories.addAll(chatHistories22);
            Collections.sort(chatHistories, Comparator.comparing(ChatHistory::getDate));

            ChatHistory newChat=chatHistories.get(chatHistories.size()-1);
           String newContent=newChat.getContent();
           Date newDate=newChat.getDate();
           String type=newChat.getType();
             ChatHistoryCategory chatHistoryCategory = new ChatHistoryCategory();
            chatHistoryCategory.setAvatar(avatar).setNewDate(newDate)
                    .setUsername( username).setContent(newContent).setType( type).setReceiverId(integer).setReadCount(readcount);
            chatHistoryCategoryList.add(chatHistoryCategory);
        }
        System.out.println("chatHistoryCategoryList = " + chatHistoryCategoryList);
        return chatHistoryCategoryList;
    }

    @Override
    public boolean importAll() {
        try{
           chatHistoryDao.deleteAll();
            List<ChatHistory> all = chatHistoryMapper.findAll();
            for (ChatHistory chatHistory : all) {
                chatHistory.setDate(new Date(chatHistory.getDate().getTime()+1000*60*60*8));
                    chatHistoryDao.save(chatHistory);
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public void clearNoRead(Integer userId, Integer receiverId) {
        List<ChatHistory> list=chatHistoryDao.findAllBySenderIdAndReceiverIdOrderByDate(receiverId,userId);
        List<ChatHistory>list1=new ArrayList<>();
        for (ChatHistory chatHistory : list) {
            if(!chatHistory.getIsRead()){
                System.out.println("数据库开始更新数据了");
                System.out.println("更新前的数据"+chatHistory);
                chatHistory.setIsRead(true);
                System.out.println("更新后的数据"+chatHistory);
                chatHistoryMapper.updateByPrimaryKeySelective(chatHistory);
                list1.add(chatHistory);
            }

        }

        System.out.println("es即将插入的数据"+list1);
            System.out.println("ES开始更新数据了");
            chatHistoryDao.saveAll(list1);


        }

    @Override
    public void findAll() {
        Iterable<ChatHistory> iterable = chatHistoryDao.findAll();
        List<ChatHistory> result = new ArrayList<>();
        iterable.forEach(result::add);
        System.out.println("result = " + result);

    }


}

